// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import {
  Form,
  Popconfirm,
  Upload,
  message,
  Button,
  Modal,
  Table,
  Row,
  Col,
  Input,
  Divider,
  Tooltip,
  Icon,
  Tabs,
  Spin
} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import config from 'config/config'

// 当前组件样式
import styles from './liveListStyle.less'
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'
const download = require("downloadjs")
const { TabPane } = Tabs;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const liveListView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  // modelObj.xxx获取model中状态机的值
  let { areaList, modalObj, checkBtn, codeQuery, codeList, biz, livePersonVisible, liveId, showModal, imgLoading, zmzjCode, zysqCode, liveStreamingModel, liveStreamingData } = modelObj



  function detailSkip(type, item) {
    let { id } = item
    hashHistory.push({
      pathname: '/home/infoAdmin/liveDetail',
      query: { actionType: type, id }
    })
  }

  function statisticsSkip(type, item) {
    let { id } = item
    hashHistory.push({
      pathname: '/home/infoAdmin/liveStatistics',
      query: { actionType: type, id }
    })
  }

  function previewSkip(item) {
    let { id, counselorAccountId, projectId, productId, uuseeConfigName, uuseeAppId } = item;
    let params = {
      liveBroadcastId: id,
      accountId: counselorAccountId
    }
    let page = `subPackages2/pages/liveRoom/wxcodeTransferStation/wxcodeTransferStation`;
    if (uuseeAppId != config.zmzjAppKey) {
      params = {
        projectId: projectId,
        productId: productId
      }
      page = `subPackages3/pages/liveManage/liveList/liveList`;
    }
    dispatch({
      type: `${namespace}/generateQrCode`,
      payload: {
        params: params,
        page: page,
      }
    })
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { showModal: true }
    });
  }

  function hideModal() {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { showModal: false }
    });
  }



  function deleteSkip(payload) {
    if (payload.published == 1) {
      message.warn('已发布的直播不允许删除')
      return
    }
    dispatch({
      type: `${namespace}/deleteLive`,
      payload: { id: payload.id }
    })
  }


  //打开观看人数列表模态框
  function openLivePersonModal(flag = false, obj = {}) {
    livePersonVisible = flag;
    let id = "";
    if (obj != null && obj != undefined) {
      id = obj.id;
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { livePersonVisible: livePersonVisible, liveId: id }
    })
  }

  // 打开直播列表模态框
  function openLiveStreaming(params) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { liveStreamingModel: true }
    })
    dispatch({
      type: `${namespace}/queryByLiveBroadcastId`,
      payload: { liveBroadcastId: params.id }
    })
  }
  // 关闭直播列表模态框
  function closeliveStreaming(params) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { liveStreamingModel: false }
    })
  }
  // 视频时长
  function formatTime(a) {
    var h = 0,
      i = 0,
      s = parseInt(a);
    if (s > 60) {
      i = parseInt(s / 60);
      s = parseInt(s % 60);
      if (i > 60) {
        h = parseInt(i / 60);
        i = parseInt(i % 60);
      }
    }
    // 补零
    var zero = function (v) {
      return v >> 0 < 10 ? "0" + v : v;
    };
    let h2 = zero(h);
    let i2 = zero(i);
    let s2 = zero(s);
    let ok = "";
    if (h2 <= 0) {
      ok = [i2, s2].join(":");
    } else {
      ok = [h2, i2, s2].join(":");
    }
    return ok;
  }

  function downFile(url){
    download(url);
  }


  let livePersonProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': 'admin/liveBroadcast/audience/' + liveId,
      // "api_url": "admin/housetype/list",
      // 接口方式
      // 'data_field_name':'result.records',
      // 'data_pageNo':'result.current',
      // 'data_pageSize':'result.size',
      // 'data_total':'result.total',
      'method': 'GET',
      'app': 'isales-mgmt-application',
      // 接口参数
      'params': '',
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 数据表格
      'table': {
        'status_params': 'status=0',
        'status_text': '全部',
        'scroll': { x: 1000 },
        'action_props': { width: 200 },
        // 表头字段列表"
        'fields': [
          {
            en_name: "key",
            zh_name: "序号",
            width: 60,
            render: (a, item, index, d, e, f) => {
              return index + 1
            },
          },
          {
            'en_name': 'nickname',
            'zh_name': '观众昵称',
            width: 200,
          },
          {
            'en_name': 'mobile',
            'zh_name': '手机号码',
            width: 200
          },
          {
            'en_name': 'counselorName',
            'zh_name': '顾问姓名',
            width: 200
          },
          {
            'en_name': 'counselorMobile',
            'zh_name': '顾问手机号',
            width: 200
          },
          {
            'en_name': 'cityName',
            'zh_name': '城市',
            width: 200,
          },
          {
            'en_name': 'createTime',
            'zh_name': '首次访问时间',
            width: 200
          },
          {
            'en_name': 'times',
            'zh_name': '观看次数',
            width: 200
          },
          {
            'en_name': 'watchTime',
            'zh_name': '观看时长(分钟)',
            width: 200
          },
        ],
      },
      // 操作栏
      // action_bar: [
      //   {
      //     'func_name': 'ex',
      //     'label': '导出',
      //     // btnId: '20501',
      //     'type': 'primary',
      //     'onClick': (e) => {
      //       console.log(e);
      //       dispatch({
      //         type: `${namespace}/downLoad`,
      //         payload: {}
      //       }) 
      //     }
      //   },
      // ],
    },
  };

  // }
  // 分页表格属性配置
  let pageProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': 'admin/liveBroadcast/queryList',
      // 接口方式
      'method': 'POST',
      'app': '',
      // 接口参数
      'params': '',
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 查询栏
      'search_bar': {
        'fields': [
          {
            en_name: 'province',
            zh_name: '省市',
            elem_type: 'Cascader',
            elem_valid_type: 'string',
            cmpt_items: areaList,
            //关联的更改的搜索字段 
            related_key: 'productId',
            //请求地址
            related_req_url: 'admin/estate/adminList',
            //默认请求
            related_req_param: {
              pageNo: 1,
              pageSize: 1000
            },
            split_keys: ['provinceCode', 'cityCode'],
          },
          {
            en_name: 'productId',
            zh_name: '项目名称',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: []
          },
          {
            en_name: 'title',
            zh_name: '直播标题',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'type',
            zh_name: '直播类型',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
              {
                value: '3',
                label: '预告'
              },
              {
                value: '1',
                label: '直播'
              },
              {
                value: '2',
                label: '回放'
              }
            ]
          },
          {
            en_name: 'validTime',
            zh_name: '直播时间',
            elem_type: 'Date',
            format: 'YYYY-MM-DD',
            // query_format: "YYYY-MM-DD HH:mm:ss",   // 请求参数, 当请求参数和显示时格式不同可通过该参数区分
            // double: true,  // 日期范围组件 使用"YYYY-MM-DD HH:mm:ss"格式时, 显示不全时可使用该参数, 将占据两格位置
            split_keys: ['gtEffectiveStartTime', 'effectiveStartTime'],
            elem_valid_type: 'string'
          }
        ],
        getDiyDom: () => {
          return <div className={styles.diyDom}>
            <Tooltip title="观看人数：统计从置业神器进入直播的客户数，同一个客户只算一次">统计口径：<Icon className={styles.iconTooltip} type="question-circle" /></Tooltip>
          </div>
        },
        searchHandler: (p) => { // 自定义搜索按钮回调函数，点击搜索时触发
          let { projectId, provinceCode } = biz.queryForm
          if (!projectId) {
            delete biz.queryForm.projectId
          }
          if (provinceCode) {
            delete biz.queryForm.provinceCode
          }

        },
        resetHandler: (p) => { // 自定义重置按钮回调函数，点击重置时触发
          // console.log('reset click', p)
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          // console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table': {
        'status_params': 'status=0',
        'status_text': '全部',
        'scroll': { x: 1600 },
        // 表头字段列表"
        'fields': [
          {
            en_name: "key",
            zh_name: "序号",
            width: "60",
            render: (a, item, index, d, e, f) => {
              return index + 1
            },
          },
          {
            'en_name': 'city',
            'zh_name': '城市',
            width: 200,
            render: (a, item, index, d, e, f) => {
              // console.log(a, item, index, d, e, f)
              return <span>{item.provinceName}-{item.cityName}</span>
            }
          },
          {
            'en_name': 'productName',
            'zh_name': '项目',
            width: 200
          },
          {
            'en_name': 'title',
            'zh_name': '直播标题',
            width: 200
          },
          {
            'en_name': 'uuseeConfigName',
            'zh_name': '直播平台',
            width: 90
          },
          {
            'en_name': 'type',
            'zh_name': '直播类型',
            width: 90,
            render: (a, item, index, d, e, f) => {
              return <span>{{ 1: '直播', 2: '回放', 3: '预告' }[a]}</span>
            }
          },
          {
            'en_name': 'published',
            'zh_name': '发布状态',
            width: 90,
            render: (a, item, index, d, e, f) => {
              return <span>{{ 0: '未发布', 1: '已发布' }[a]}</span>
            }
          },
          {
            'en_name': 'counselorName',
            'zh_name': '主播',
            width: 100
          },
          {
            'en_name': 'numberOfVisitors',
            'zh_name': '观看人数',
            width: 90,
            render: (a, item, index, d, e, f) => {
              if (item.numberOfVisitors != 0) {
                return <a style={{ color: 'blue' }} onClick={() => openLivePersonModal(true, item)}>{item.numberOfVisitors}</a>;
              }
              return item.numberOfVisitors;
            }
          },
          {
            'en_name': 'data',
            'zh_name': '直播时间',
            width: 180,
            render: (a, item, index, d, e, f) => {
              return (
                <div>
                  <div>{item.effectiveStartTime}</div>
                  <div>{item.effectiveEndTime}</div>
                </div>
              )

            }
          },
          {
            'en_name': 'createPerson',
            'zh_name': '创建人',
            width: 100,
          },
          {
            'en_name': 'createTime',
            'zh_name': '创建时间',
            width: 180
          },
          {
            en_name: "edit",
            zh_name: "操作",
            width: 150,
            fixed: 'right',
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  {(item.type == 1 || item.type == 2) &&
                    <FlagBtn node={<a onClick={() => openLiveStreaming(item)}>直播视频<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn>}
                  {item.published == 1 &&
                    <FlagBtn node={<a onClick={() => previewSkip(item)}>二维码<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn>}
                  <FlagBtn node={<a onClick={() => detailSkip('check', item)}>查看<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => detailSkip('edit', item)}>编辑<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => statisticsSkip('check', item)}>统计<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn>
                  <FlagBtn node={<Popconfirm Collapse title={`确定要删除吗？`} okText='确定' cancelText='取消' onConfirm={() => deleteSkip(item)}>
                    <a href='javascript:void(0)' onClick={(e) => { }}>删除
                          </a>
                  </Popconfirm>} btnId={''}> </FlagBtn>
                </span>
              )
            },
          }

        ],

        'actions': [
        ],
        "action_props": {
          fixed: "right",
          width: 210
        }
      },
      // 操作栏
      action_bar: [
        {
          'func_name': 'add',
          'label': '新增直播',
          btnId: '',
          'type': 'primary',
          'onClick': (e) => {
            hashHistory.push({
              pathname: '/home/infoAdmin/liveDetail',
              query: { actionType: 'add' }
            })
          }
        }
      ]
    },
  }
  let liveStreamingList = [
    {
      title: '序号',
      dataIndex: '',
      key: '',
      width: 40,
      render: (a, item, index) => (index + 1)
    },
    {
      title: '直播视频地址',
      dataIndex: 'videoUrl',
      key: 'videoUrl',
    },
    {
      title: '视频时长',
      dataIndex: 'times',
      key: 'times',
      width: 80,
      render: function(a, item, index, d, e, f) {
        // 返回时间为秒
        let startTime = item.startTime
        let endTime = item.endTime
        let s = endTime - startTime;
        return formatTime(s)
      }
    },
    {
      title: '操作',
      dataIndex: 'canDO',
      key: 'canDO',
      width: 100,
      render: (a, item, index, d, e, f) => {
        return (
          <span>
            <FlagBtn node={<a target="_blank" href={item.videoUrl}>查看<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn>
            <FlagBtn node={<a onClick={()=> downFile(item.videoUrl)}>下载<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={''}> </FlagBtn>
          </span>
        )
      }
    }
  ]

  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }

  return (
    <div className={cx('pageLayout')}>
      <ListPage pageProps={pageProps} />
      <Modal
        title={'观看人数列表'}
        visible={livePersonVisible}
        okText={'导出'}
        onOk={() => {
          dispatch({
            type: `${namespace}/downLivePerson`,
            payload: { liveId: liveId }
          })
        }}
        onCancel={() => {
          openLivePersonModal(false)
        }}
        width={'80%'}
      >
        {livePersonVisible && <ListPage pageProps={livePersonProps} />}
      </Modal>
      <Modal
        maskClosable={true}
        onCancel={() => { hideModal() }}
        visible={showModal}
        footer={null}>
        <Tabs defaultActiveKey="2" size={'small'}>
          <TabPane tab="美的置业云" key="2">
            {
              imgLoading ?
                <div className={styles.codeClass}>
                  <Spin tip='Loading...' size='large'></Spin>
                </div> :
                <img className={styles.codeClass} src={zmzjCode} />
            }

          </TabPane>
          {/* <TabPane tab="置业神器" key="1">
            {
              imgLoading?
                  <div className={styles.codeClass}>
                    <Spin tip='Loading...' size='large'></Spin>
                  </div> :
                  <img className={styles.codeClass} src={zysqCode}/>
            }
          </TabPane> */}
        </Tabs>
      </Modal>

      <Modal
        title="直播视频列表"
        visible={liveStreamingModel}
        onCancel={() => closeliveStreaming()}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <Table className="live-su" columns={liveStreamingList} dataSource={liveStreamingData} />
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(liveListView))